package com.landis.temple.mobile;

import android.app.Activity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Activity handles the creation of both stories and chapters depending on how created
 * 
 * @author John Landis 
 * @author Anton Kronaj
 * 
 */
public class CreateActivity extends Activity implements OnClickListener 
{
    private static final String TAG = "CreateActivity";
    private TwitterStoryDatabase tsdb;
    
    // Default invalid values
    private int  action     = -1; 
    private long author_id  = -1;
    private long story_id   = -1;
    private TextView userView;		// for the username display
    
    /**
     * called when the activity is first created.
     * creates either a chapter or a story depending on the action passed to this activity as an extra.
     *  
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.create );

        userView = new TextView( this );
        userView = (TextView) findViewById( R.id.username );
        if(TwitterLibrary.userName != null) userView.setText( TwitterLibrary.userName );
        
        Log.d( TAG , "in onCreate" );
        
        action = getIntent().getExtras().getInt("action");
        author_id = getIntent().getExtras().getLong("author_id");
        
        Log.d( TAG , "action : " + action );
        Log.d( TAG , "author_id : " + author_id );        
        
        // Return if invalid values supplied
        if( action == -1 || author_id == -1 ) finish();
        
        switch( action ) 
        {
            case TwitterLibrary.CREATE_CHAPTER:
                
                findViewById(R.id.chapter_text).setVisibility(View.VISIBLE);
                
                ( (TextView) findViewById( R.id.create_title ) ).setText( R.string.create_chapter );
                
                story_id = getIntent().getExtras().getLong("story_id");                
                Log.d( TAG , "story_id : " + story_id );
                
                if( story_id == -1 ) finish();
                
                break;
                
            case TwitterLibrary.CREATE_STORY :
                
                findViewById(R.id.title_text).setVisibility(View.VISIBLE);
                ( (TextView) findViewById( R.id.create_title ) ).setText( R.string.create_story );
                
                break;
        }
        findViewById(R.id.commit_button).setOnClickListener( this );    
    }

    /**
     * story or chapter is created on button click
     * 
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     * 
     */
    @Override
    public void onClick(View button) 
    {
        Log.d( TAG , "onClick" );
    	
        // Create database if necessary
        if( tsdb == null )
        {
            tsdb = new TwitterStoryDatabase(this.getApplicationContext());
            tsdb.open();
        }
                        
        switch( action ) 
        {
            case TwitterLibrary.CREATE_CHAPTER :
                String text = ((EditText)findViewById(R.id.chapter_text)).getText().toString();
                
                // Check field is not blank
                if( text.equals("") || text.equals( getString(R.string.error) ) ) 
                {
                    ((EditText)findViewById(R.id.chapter_text)).setText( R.string.error );
                    return;
                }
                Log.d( TAG , "Creating chapter story_id = " + story_id + ", author_id = " + author_id + " , text = " + text);
                tsdb.createChapter( story_id , author_id, text);
                MySQLAccess.addChapter( tsdb.getAuthor( author_id ) , tsdb.getStoryTitle( story_id ) , text);
                new Tweet().execute( text );
                break;
                
            case TwitterLibrary.CREATE_STORY :
                String title = ((EditText)findViewById(R.id.title_text)).getText().toString();
                
                // Check field is not blank
                if( title.equals("") || title.equals( getString( R.string.error ) ) ) 
                {
                    ((EditText)findViewById(R.id.title_text)).setText( R.string.error );
                    return;
                }

                tsdb.createStory( author_id, title );
                MySQLAccess.addStory( tsdb.getAuthor( author_id ) , title );
                new Tweet().execute( title );
                break;
        }
        
        setResult( RESULT_OK );
        finish();
    }
    
    /**
     * closes twitter story databse when the ctivity enters the onDestroy phase.
     * @see android.app.Activity#onDestroy()
     */
    @Override
    protected void onDestroy() 
    {
        Log.d( TAG , "in onDestroy" );
        super.onDestroy();
        if( tsdb != null ) tsdb.close();
    }
    
    /**
     * 
     * @author John Landis
     * @author Anton Kronaj
     * 
     * Async class for tweeting - Needs to be located inside an activity for safe UI updating
     *
     */
    private class Tweet extends AsyncTask< String , Void , String >
    {
        @Override
        protected String doInBackground(String... tweets) 
        {
            TwitterBackend.tweet(tweets[0], CreateActivity.this );
            return tweets[0];
        }
        
        @Override
        protected void onPostExecute( String tweet ) 
        {
            Toast.makeText( CreateActivity.this , tweet, Toast.LENGTH_LONG).show();
            super.onPostExecute( tweet );
        }
    }

    // Activity Life Cycle Functions 
    // Unchanged except for added logging information
    
    /**
     * not used
     * @see android.app.Activity#onPause()
     */
    @Override
    protected void onPause() 
    {
        Log.d( TAG , "in onPause" );
        super.onPause();
    }

    /**
     * not used
     * @see android.app.Activity#onRestart()
     */
    @Override
    protected void onRestart() 
    {
        Log.d( TAG , "in onRestart" );
        super.onRestart();
    }

    /**
     * not used
     * @see android.app.Activity#onResume()
     */
    @Override
    protected void onResume() 
    {
        Log.d( TAG , "in onResume" );
        super.onResume();
    }

    @Override
    protected void onStart() 
    {
        Log.d( TAG , "in onStart" );
        super.onStart();
    }

    @Override
    protected void onStop() 
    {
        Log.d( TAG , "in onStop" );
        super.onStop();
    }
}
